#!/usr/bin/perl
#save_create.cgi

require './diskman-lib.pl';

&ReadParse();

my ($err_msg, $log_ev, $log_msg, $log_pri);

$err_msg="";
$log_ev="";
my $mkfs_lock;
$mkfs_lock = check_lock();
if ($mkfs_lock) {
        `touch /root/mflock`;
	$err_msg = $text{"err_mkfslocked"};
	goto ERROR_OUT;
}
my ($level, $disklist, $volname, $needspare, $sparedisk);

$level = $in{'level'};
$disklist = $in{'listinput'};
$volname = $in{'volname'};
my (@rdinfo, @dinfo, @free_volumes, $i);

@rdinfo = new_get_check_raid_info();
@dinfo = new_get_diskinfo();

@free_volumes = get_free_volumes(\@rdinfo);

my ($fv, $found);
$found = 0;
foreach $fv (@free_volumes) {
	if ($fv eq $volname) {
		$found = 1;
		last;
	}
}

if (!$found) {
	$err_msg = $text{"err_configchanged"};
	#goto ERROR_OUT;
}

my (@diskname, $dn);
@diskname = split(/\s+/, $disklist);
$pp=0;
$dlist = "";
foreach $dl (@diskname){
	if($pp==0){
		$dlist = $dl+8;
	}
	else{
		$dlist = $dlist.",".($dl+8);
	}
	$pp++;
}
my (@rdevs);
if ($level == 0) {
	if (@rdevs < 1) {
		$err_msg = $text{"err_cgiparam"};
	}
}
elsif ($level == 1) {
	if (@rdevs < 2) {
		$err_msg = $text{"err_cgiparam"};
	}
}
elsif ($level == 5) {
	if (@rdevs < 3) {
		$err_msg = $text{"err_cgiparam"};
	}
}

# check finished

my ($mddev);
$mddev = get_free_scsi_dev();
$err_msg =  $level." ".$dlist." ".$volname;

@rsinfo = get_rs_info();
$freersid = get_free_rsid(@rsinfo);

my ($rc);
$rc = new_create_volume($level, $dlist, $volname, $freersid);

if ($rc) {
	$log_ev = $text{'log_ev_crtvolume_err'};
	$log_msg= &text('log_msg_crtvolume_err', $volname, 'RAID '.$level);
	nas_syslog($text{'my_log_minor'}, 'naslog_warning', $log_ev, $log_msg);

	$err_msg = $text{'err_crtvol'};
	goto ERROR_OUT;
}

$log_ev = $text{'log_ev_crtvolume_ok'};
$log_msg= &text('log_msg_crtvolume_ok', $volname, 'RAID '.$level);
nas_syslog($text{'my_log_minor'}, 'naslog_info', $log_ev, $log_msg);

#`/sbin/reboot`;

$err_msg = $mddev;
#goto ERROR_OUT;
redirect("index.cgi");
# Create Physical Volume(PV)
sleep 10;
`/sbin/lvm pvcreate $mddev`;
ERROR_OUT:
&error_setup($text{'crt_err_title'});
&error($err_msg);
